{% extends "base.html" %}

{% block title %}{{ ts_code }} - 股票详情 - 股票分析系统{% endblock %}

{% block content %}
<div class="container">
    <!-- 股票基本信息 -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <div class="d-flex justify-content-between align-items-center">
                        <h5 class="mb-0">📊 股票详情</h5>
                        <span class="badge bg-primary" id="stock-code">{{ ts_code }}</span>
                    </div>
                </div>
                <div class="card-body">
                    <div id="stock-info" class="row">
                        <div class="col-12 text-center py-3">
                            <div class="spinner-border text-primary" role="status">
                                <span class="visually-hidden">加载中...</span>
                            </div>
                            <p class="mt-2 text-muted">正在加载股票信息...</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 功能选项卡 -->
    <div class="row">
        <div class="col-12">
            <ul class="nav nav-tabs" id="stockTabs" role="tablist">
                <li class="nav-item" role="presentation">
                    <button class="nav-link active" id="history-tab" data-bs-toggle="tab" data-bs-target="#history" type="button" role="tab">
                        📈 历史数据
                    </button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="factors-tab" data-bs-toggle="tab" data-bs-target="#factors" type="button" role="tab">
                        🔢 技术因子
                    </button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="moneyflow-tab" data-bs-toggle="tab" data-bs-target="#moneyflow" type="button" role="tab">
                        💰 资金流向
                    </button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="cyq-tab" data-bs-toggle="tab" data-bs-target="#cyq" type="button" role="tab">
                        🎯 筹码分布
                    </button>
                </li>
            </ul>
            
            <div class="tab-content" id="stockTabsContent">
                <!-- 历史数据 -->
                <div class="tab-pane fade show active" id="history" role="tabpanel">
                    <div class="card">
                        <div class="card-header">
                            <div class="d-flex justify-content-between align-items-center">
                                <h6 class="mb-0">历史价格数据</h6>
                                <div class="btn-group btn-group-sm" role="group">
                                    <button type="button" class="btn btn-outline-primary" onclick="loadHistoryData(30)">30天</button>
                                    <button type="button" class="btn btn-outline-primary active" onclick="loadHistoryData(60)">60天</button>
                                    <button type="button" class="btn btn-outline-primary" onclick="loadHistoryData(120)">120天</button>
                                </div>
                            </div>
                        </div>
                        <div class="card-body">
                            <div id="history-content">
                                <div class="text-center py-4">
                                    <p class="text-muted">点击上方按钮加载历史数据</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 技术因子 -->
                <div class="tab-pane fade" id="factors" role="tabpanel">
                    <div class="card">
                        <div class="card-header">
                            <h6 class="mb-0">技术因子数据</h6>
                        </div>
                        <div class="card-body">
                            <div id="factors-content">
                                <div class="text-center py-4">
                                    <p class="text-muted">切换到此标签页时自动加载</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 资金流向 -->
                <div class="tab-pane fade" id="moneyflow" role="tabpanel">
                    <div class="card">
                        <div class="card-header">
                            <h6 class="mb-0">资金流向数据</h6>
                        </div>
                        <div class="card-body">
                            <div id="moneyflow-content">
                                <div class="text-center py-4">
                                    <p class="text-muted">切换到此标签页时自动加载</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 筹码分布 -->
                <div class="tab-pane fade" id="cyq" role="tabpanel">
                    <div class="card">
                        <div class="card-header">
                            <h6 class="mb-0">筹码分布数据</h6>
                        </div>
                        <div class="card-body">
                            <div id="cyq-content">
                                <div class="text-center py-4">
                                    <p class="text-muted">切换到此标签页时自动加载</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
const tsCode = '{{ ts_code }}';
let stockInfo = null;

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    loadStockInfo();
    loadHistoryData(60); // 默认加载60天数据
    
    // 绑定标签页切换事件
    document.querySelectorAll('#stockTabs button[data-bs-toggle="tab"]').forEach(tab => {
        tab.addEventListener('shown.bs.tab', function(event) {
            const target = event.target.getAttribute('data-bs-target');
            switch(target) {
                case '#factors':
                    loadFactorsData();
                    break;
                case '#moneyflow':
                    loadMoneyflowData();
                    break;
                case '#cyq':
                    loadCyqData();
                    break;
            }
        });
    });
});

// 加载股票基本信息
async function loadStockInfo() {
    try {
        const response = await apiRequest(`/stocks/${tsCode}`);
        if (response.code === 200) {
            stockInfo = response.data;
            renderStockInfo(stockInfo);
        } else {
            showError('stock-info', '股票信息加载失败');
        }
    } catch (error) {
        showError('stock-info', '股票信息加载失败');
        console.error('加载股票信息失败:', error);
    }
}

// 渲染股票基本信息
function renderStockInfo(stock) {
    const container = document.getElementById('stock-info');
    
    const html = `
        <div class="col-md-8">
            <h3 class="mb-3">${stock.name} <small class="text-muted">(${stock.symbol})</small></h3>
            <div class="row g-3">
                <div class="col-md-6">
                    <div class="d-flex justify-content-between">
                        <span class="text-muted">股票代码:</span>
                        <strong>${stock.ts_code}</strong>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="d-flex justify-content-between">
                        <span class="text-muted">股票简称:</span>
                        <strong>${stock.symbol}</strong>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="d-flex justify-content-between">
                        <span class="text-muted">所属行业:</span>
                        <span class="badge bg-secondary">${stock.industry || '--'}</span>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="d-flex justify-content-between">
                        <span class="text-muted">所属地域:</span>
                        <span class="badge bg-info">${stock.area || '--'}</span>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="d-flex justify-content-between">
                        <span class="text-muted">上市日期:</span>
                        <strong>${stock.list_date || '--'}</strong>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="d-flex justify-content-between">
                        <span class="text-muted">市场:</span>
                        <span class="badge ${stock.ts_code.includes('SH') ? 'bg-danger' : 'bg-success'}">
                            ${stock.ts_code.includes('SH') ? '上海' : '深圳'}
                        </span>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="text-center">
                <div class="card bg-light">
                    <div class="card-body">
                        <h5 class="card-title">快速操作</h5>
                        <div class="d-grid gap-2">
                            <button class="btn btn-primary btn-sm" onclick="addToWatchlist()">
                                ⭐ 加入自选
                            </button>
                            <button class="btn btn-success btn-sm" onclick="openAnalysis()">
                                📈 技术分析
                            </button>
                            <button class="btn btn-info btn-sm" onclick="openBacktest()">
                                📊 策略回测
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    container.innerHTML = html;
}

// 加载历史数据
async function loadHistoryData(days = 60) {
    showLoading('history-content');
    
    try {
        const response = await apiRequest(`/stocks/${tsCode}/history?limit=${days}`);
        if (response.code === 200) {
            renderHistoryData(response.data, days);
        } else {
            showError('history-content', '历史数据加载失败');
        }
    } catch (error) {
        showError('history-content', '历史数据加载失败');
        console.error('加载历史数据失败:', error);
    }
}

// 渲染历史数据
function renderHistoryData(data, days) {
    const container = document.getElementById('history-content');
    
    if (!data || data.length === 0) {
        container.innerHTML = '<div class="text-center py-4"><p class="text-muted">暂无历史数据</p></div>';
        return;
    }
    
    const html = `
        <div class="mb-3">
            <small class="text-muted">最近 ${days} 天的历史数据，共 ${data.length} 条记录（按时间倒序，最新数据在前）</small>
        </div>
        <div class="table-responsive">
            <table class="table table-sm table-hover">
                <thead>
                    <tr>
                        <th>日期</th>
                        <th>开盘价</th>
                        <th>最高价</th>
                        <th>最低价</th>
                        <th>收盘价</th>
                        <th>成交量(万手)</th>
                        <th>成交额(万元)</th>
                        <th>涨跌幅</th>
                    </tr>
                </thead>
                <tbody>
                    ${data.slice(0, 20).map(item => `
                        <tr>
                            <td><strong>${item.trade_date || '--'}</strong></td>
                            <td>${formatNumber(item.open, 2)}</td>
                            <td class="text-danger">${formatNumber(item.high, 2)}</td>
                            <td class="text-success">${formatNumber(item.low, 2)}</td>
                            <td class="text-primary"><strong>${formatNumber(item.close, 2)}</strong></td>
                            <td>${formatNumber((item.vol || 0) / 10000, 1)}</td>
                            <td>${formatNumber((item.amount || 0) / 10000, 0)}</td>
                            <td class="${(item.pct_chg || 0) >= 0 ? 'text-danger' : 'text-success'}">
                                <strong>${formatPercent(item.pct_chg || 0)}</strong>
                            </td>
                        </tr>
                    `).join('')}
                </tbody>
            </table>
        </div>
        ${data.length > 20 ? `<div class="text-center"><small class="text-muted">仅显示前20条记录</small></div>` : ''}
    `;
    
    container.innerHTML = html;
}

// 加载技术因子数据
async function loadFactorsData() {
    if (document.getElementById('factors-content').innerHTML.includes('加载中')) return;
    
    showLoading('factors-content');
    
    try {
        const response = await apiRequest(`/stocks/${tsCode}/factors?limit=20`);
        if (response.code === 200) {
            renderFactorsData(response.data);
        } else {
            showError('factors-content', '技术因子数据加载失败');
        }
    } catch (error) {
        showError('factors-content', '技术因子数据加载失败');
        console.error('加载技术因子数据失败:', error);
    }
}

// 渲染技术因子数据
function renderFactorsData(data) {
    const container = document.getElementById('factors-content');
    
    if (!data || data.length === 0) {
        container.innerHTML = '<div class="text-center py-4"><p class="text-muted">暂无技术因子数据</p></div>';
        return;
    }
    
    const html = `
        <div class="mb-3">
            <small class="text-muted">技术因子数据，共 ${data.length} 条记录（按时间倒序，最新数据在前）</small>
        </div>
        
        <!-- 技术指标图表 -->
        <div class="row mb-4">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h6 class="mb-0">📊 技术指标趋势</h6>
                    </div>
                    <div class="card-body">
                        <div id="factors-chart" style="height: 400px;"></div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 详细数据表格 -->
        <div class="card">
            <div class="card-header">
                <h6 class="mb-0">📋 详细数据</h6>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-sm table-hover">
                        <thead>
                            <tr>
                                <th>日期</th>
                                <th>收盘价</th>
                                <th>MACD DIF</th>
                                <th>MACD DEA</th>
                                <th>MACD</th>
                                <th>KDJ K</th>
                                <th>KDJ D</th>
                                <th>KDJ J</th>
                                <th>RSI(6)</th>
                                <th>RSI(12)</th>
                                <th>RSI(24)</th>
                                <th>布林上轨</th>
                                <th>布林中轨</th>
                                <th>布林下轨</th>
                                <th>CCI</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${data.slice(0, 20).map(item => `
                                <tr>
                                    <td><strong>${item.trade_date || '--'}</strong></td>
                                    <td class="text-primary"><strong>${formatNumber(item.close, 2)}</strong></td>
                                    <td class="${(item.macd_dif || 0) >= 0 ? 'text-danger' : 'text-success'}">${formatNumber(item.macd_dif, 4)}</td>
                                    <td class="${(item.macd_dea || 0) >= 0 ? 'text-danger' : 'text-success'}">${formatNumber(item.macd_dea, 4)}</td>
                                    <td class="${(item.macd || 0) >= 0 ? 'text-danger' : 'text-success'}">${formatNumber(item.macd, 4)}</td>
                                    <td>${formatNumber(item.kdj_k, 2)}</td>
                                    <td>${formatNumber(item.kdj_d, 2)}</td>
                                    <td class="${(item.kdj_j || 0) > 80 ? 'text-danger' : (item.kdj_j || 0) < 20 ? 'text-success' : ''}">${formatNumber(item.kdj_j, 2)}</td>
                                    <td class="${(item.rsi_6 || 0) > 70 ? 'text-danger' : (item.rsi_6 || 0) < 30 ? 'text-success' : ''}">${formatNumber(item.rsi_6, 2)}</td>
                                    <td class="${(item.rsi_12 || 0) > 70 ? 'text-danger' : (item.rsi_12 || 0) < 30 ? 'text-success' : ''}">${formatNumber(item.rsi_12, 2)}</td>
                                    <td class="${(item.rsi_24 || 0) > 70 ? 'text-danger' : (item.rsi_24 || 0) < 30 ? 'text-success' : ''}">${formatNumber(item.rsi_24, 2)}</td>
                                    <td class="text-danger">${formatNumber(item.boll_upper, 2)}</td>
                                    <td class="text-warning">${formatNumber(item.boll_mid, 2)}</td>
                                    <td class="text-success">${formatNumber(item.boll_lower, 2)}</td>
                                    <td class="${(item.cci || 0) > 100 ? 'text-danger' : (item.cci || 0) < -100 ? 'text-success' : ''}">${formatNumber(item.cci, 2)}</td>
                                </tr>
                            `).join('')}
                        </tbody>
                    </table>
                </div>
                ${data.length > 20 ? `<div class="text-center mt-3"><small class="text-muted">仅显示前20条记录</small></div>` : ''}
            </div>
        </div>
    `;
    
    container.innerHTML = html;
    
    // 渲染技术指标图表
    renderFactorsChart(data);
}

// 渲染技术指标图表
function renderFactorsChart(data) {
    const factorsChart = echarts.init(document.getElementById('factors-chart'));
    
    // 数据需要反转，因为ECharts期望时间正序
    const reversedData = [...data].reverse();
    const dates = reversedData.map(item => item.trade_date);
    
    const factorsOption = {
        title: {
            text: '技术指标趋势',
            left: 'center'
        },
        tooltip: {
            trigger: 'axis',
            formatter: function(params) {
                let result = params[0].name + '<br/>';
                params.forEach(param => {
                    result += param.marker + param.seriesName + ': ' + formatNumber(param.value, 4) + '<br/>';
                });
                return result;
            }
        },
        legend: {
            data: ['MACD DIF', 'MACD DEA', 'MACD', 'RSI(6)', 'RSI(12)', 'KDJ K', 'KDJ D'],
            top: 30,
            type: 'scroll'
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '15%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: dates,
            axisLabel: {
                rotate: 45
            }
        },
        yAxis: [
            {
                type: 'value',
                name: 'MACD',
                position: 'left',
                axisLabel: {
                    formatter: function(value) {
                        return formatNumber(value, 4);
                    }
                }
            },
            {
                type: 'value',
                name: 'RSI/KDJ',
                position: 'right',
                min: 0,
                max: 100,
                axisLabel: {
                    formatter: function(value) {
                        return value + '';
                    }
                }
            }
        ],
        dataZoom: [
            {
                type: 'inside',
                start: 70,
                end: 100
            },
            {
                show: true,
                type: 'slider',
                top: '90%',
                start: 70,
                end: 100
            }
        ],
        series: [
            {
                name: 'MACD DIF',
                type: 'line',
                yAxisIndex: 0,
                data: reversedData.map(item => item.macd_dif || 0),
                itemStyle: { color: '#ff4d4f' },
                lineStyle: { width: 2 }
            },
            {
                name: 'MACD DEA',
                type: 'line',
                yAxisIndex: 0,
                data: reversedData.map(item => item.macd_dea || 0),
                itemStyle: { color: '#52c41a' },
                lineStyle: { width: 2 }
            },
            {
                name: 'MACD',
                type: 'bar',
                yAxisIndex: 0,
                data: reversedData.map(item => item.macd || 0),
                itemStyle: {
                    color: function(params) {
                        return params.value >= 0 ? '#ff4d4f' : '#52c41a';
                    }
                }
            },
            {
                name: 'RSI(6)',
                type: 'line',
                yAxisIndex: 1,
                data: reversedData.map(item => item.rsi_6 || 0),
                itemStyle: { color: '#1890ff' }
            },
            {
                name: 'RSI(12)',
                type: 'line',
                yAxisIndex: 1,
                data: reversedData.map(item => item.rsi_12 || 0),
                itemStyle: { color: '#722ed1' }
            },
            {
                name: 'KDJ K',
                type: 'line',
                yAxisIndex: 1,
                data: reversedData.map(item => item.kdj_k || 0),
                itemStyle: { color: '#fa8c16' }
            },
            {
                name: 'KDJ D',
                type: 'line',
                yAxisIndex: 1,
                data: reversedData.map(item => item.kdj_d || 0),
                itemStyle: { color: '#13c2c2' }
            }
        ]
    };
    
    factorsChart.setOption(factorsOption);
    
    // 响应式调整
    window.addEventListener('resize', function() {
        factorsChart.resize();
    });
}

// 加载资金流向数据
async function loadMoneyflowData() {
    if (document.getElementById('moneyflow-content').innerHTML.includes('加载中')) return;
    
    showLoading('moneyflow-content');
    
    try {
        const response = await apiRequest(`/stocks/${tsCode}/moneyflow?limit=20`);
        if (response.code === 200) {
            renderMoneyflowData(response.data);
        } else {
            showError('moneyflow-content', '资金流向数据加载失败');
        }
    } catch (error) {
        showError('moneyflow-content', '资金流向数据加载失败');
        console.error('加载资金流向数据失败:', error);
    }
}

// 渲染资金流向数据
function renderMoneyflowData(data) {
    const container = document.getElementById('moneyflow-content');
    
    if (!data || data.length === 0) {
        container.innerHTML = '<div class="text-center py-4"><p class="text-muted">暂无资金流向数据</p></div>';
        return;
    }
    
    const html = `
        <div class="mb-3">
            <small class="text-muted">资金流向数据，共 ${data.length} 条记录</small>
        </div>
        
        <!-- 资金流向图表 -->
        <div class="row mb-4">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">
                        <h6 class="mb-0">📊 分单资金买卖对比</h6>
                    </div>
                    <div class="card-body">
                        <div id="moneyflow-chart" style="height: 400px;"></div>
                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="card">
                    <div class="card-header">
                        <h6 class="mb-0">📈 净流入趋势</h6>
                    </div>
                    <div class="card-body">
                        <div id="netflow-chart" style="height: 400px;"></div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 资金形态指标 -->
        <div class="row mb-4">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h6 class="mb-0">💰 资金形态指标</h6>
                    </div>
                    <div class="card-body">
                        <div class="row" id="money-indicators">
                            <!-- 动态生成指标卡片 -->
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 详细数据表格 -->
        <div class="card">
            <div class="card-header">
                <h6 class="mb-0">📋 详细数据</h6>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-sm table-hover">
                        <thead>
                            <tr>
                                <th>日期</th>
                                <th>净流入额</th>
                                <th>特大单买入</th>
                                <th>特大单卖出</th>
                                <th>大单买入</th>
                                <th>大单卖出</th>
                                <th>中单买入</th>
                                <th>中单卖出</th>
                                <th>小单买入</th>
                                <th>小单卖出</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${data.slice(0, 10).map(item => `
                                <tr>
                                    <td>${item.trade_date || '--'}</td>
                                    <td class="${(item.net_mf_amount || 0) >= 0 ? 'text-danger' : 'text-success'}">
                                        <strong>${formatNumber(item.net_mf_amount, 0)}</strong>
                                    </td>
                                    <td class="text-danger">${formatNumber(item.buy_elg_amount, 0)}</td>
                                    <td class="text-success">${formatNumber(item.sell_elg_amount, 0)}</td>
                                    <td class="text-danger">${formatNumber(item.buy_lg_amount, 0)}</td>
                                    <td class="text-success">${formatNumber(item.sell_lg_amount, 0)}</td>
                                    <td class="text-danger">${formatNumber(item.buy_md_amount, 0)}</td>
                                    <td class="text-success">${formatNumber(item.sell_md_amount, 0)}</td>
                                    <td class="text-danger">${formatNumber(item.buy_sm_amount, 0)}</td>
                                    <td class="text-success">${formatNumber(item.sell_sm_amount, 0)}</td>
                                </tr>
                            `).join('')}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    `;
    
    container.innerHTML = html;
    
    // 渲染图表
    renderMoneyflowCharts(data);
}

// 渲染资金流向图表
function renderMoneyflowCharts(data) {
    // 分单资金买卖对比图
    const moneyflowChart = echarts.init(document.getElementById('moneyflow-chart'));
    
    const dates = data.map(item => item.trade_date).reverse();
    const latestData = data[0]; // 最新一天的数据
    
    // 分单买卖对比（最新一天）
    const moneyflowOption = {
        title: {
            text: '分单资金买卖对比',
            subtext: `${latestData.trade_date}`,
            left: 'center'
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            },
            formatter: function(params) {
                let result = params[0].name + '<br/>';
                params.forEach(param => {
                    const value = Math.abs(param.value);
                    result += param.marker + param.seriesName + ': ' + formatNumber(value, 0) + '万<br/>';
                });
                return result;
            }
        },
        legend: {
            data: ['买入', '卖出'],
            top: 30
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: ['特大单', '大单', '中单', '小单']
        },
        yAxis: {
            type: 'value',
            axisLabel: {
                formatter: function(value) {
                    return formatNumber(Math.abs(value), 0) + '万';
                }
            }
        },
        series: [
            {
                name: '买入',
                type: 'bar',
                data: [
                    latestData.buy_elg_amount || 0,
                    latestData.buy_lg_amount || 0,
                    latestData.buy_md_amount || 0,
                    latestData.buy_sm_amount || 0
                ],
                itemStyle: {
                    color: '#ff4d4f'
                }
            },
            {
                name: '卖出',
                type: 'bar',
                data: [
                    -(latestData.sell_elg_amount || 0),
                    -(latestData.sell_lg_amount || 0),
                    -(latestData.sell_md_amount || 0),
                    -(latestData.sell_sm_amount || 0)
                ],
                itemStyle: {
                    color: '#52c41a'
                }
            }
        ]
    };
    
    moneyflowChart.setOption(moneyflowOption);
    
    // 净流入趋势图
    const netflowChart = echarts.init(document.getElementById('netflow-chart'));
    
    const netflowOption = {
        title: {
            text: '净流入趋势',
            left: 'center'
        },
        tooltip: {
            trigger: 'axis',
            formatter: function(params) {
                const data = params[0];
                return `${data.name}<br/>净流入: ${formatNumber(data.value, 0)}万`;
            }
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '15%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: dates,
            axisLabel: {
                rotate: 45
            }
        },
        yAxis: {
            type: 'value',
            axisLabel: {
                formatter: function(value) {
                    return formatNumber(value, 0) + '万';
                }
            }
        },
        series: [{
            name: '净流入',
            type: 'line',
            data: data.map(item => item.net_mf_amount || 0).reverse(),
            itemStyle: {
                color: '#1890ff'
            },
            areaStyle: {
                color: {
                    type: 'linear',
                    x: 0,
                    y: 0,
                    x2: 0,
                    y2: 1,
                    colorStops: [{
                        offset: 0, color: 'rgba(24, 144, 255, 0.3)'
                    }, {
                        offset: 1, color: 'rgba(24, 144, 255, 0.1)'
                    }]
                }
            }
        }]
    };
    
    netflowChart.setOption(netflowOption);
    
    // 渲染资金形态指标
    renderMoneyIndicators(latestData);
    
    // 响应式调整
    window.addEventListener('resize', function() {
        moneyflowChart.resize();
        netflowChart.resize();
    });
}

// 渲染资金形态指标
function renderMoneyIndicators(data) {
    const container = document.getElementById('money-indicators');
    
    // 计算各种指标
    const totalBuy = (data.buy_elg_amount || 0) + (data.buy_lg_amount || 0) + (data.buy_md_amount || 0) + (data.buy_sm_amount || 0);
    const totalSell = (data.sell_elg_amount || 0) + (data.sell_lg_amount || 0) + (data.sell_md_amount || 0) + (data.sell_sm_amount || 0);
    const mainBuy = (data.buy_elg_amount || 0) + (data.buy_lg_amount || 0); // 主力买入（特大单+大单）
    const mainSell = (data.sell_elg_amount || 0) + (data.sell_lg_amount || 0); // 主力卖出
    
    const lgBuyRate = totalBuy > 0 ? ((data.buy_lg_amount || 0) / totalBuy * 100) : 0;
    const elgBuyRate = totalBuy > 0 ? ((data.buy_elg_amount || 0) / totalBuy * 100) : 0;
    const mainNetFlow = mainBuy - mainSell;
    
    const html = `
        <div class="col-md-3">
            <div class="text-center p-3 bg-light rounded">
                <h5 class="text-primary">${formatNumber(data.net_mf_amount || 0, 0)}</h5>
                <small class="text-muted">净流入额(万)</small>
            </div>
        </div>
        <div class="col-md-3">
            <div class="text-center p-3 bg-light rounded">
                <h5 class="text-success">${formatNumber(lgBuyRate, 1)}%</h5>
                <small class="text-muted">大单买入占比</small>
            </div>
        </div>
        <div class="col-md-3">
            <div class="text-center p-3 bg-light rounded">
                <h5 class="text-warning">${formatNumber(elgBuyRate, 1)}%</h5>
                <small class="text-muted">特大单买入占比</small>
            </div>
        </div>
        <div class="col-md-3">
            <div class="text-center p-3 bg-light rounded">
                <h5 class="${mainNetFlow >= 0 ? 'text-danger' : 'text-success'}">${formatNumber(mainNetFlow, 0)}</h5>
                <small class="text-muted">主力净流入(万)</small>
            </div>
        </div>
    `;
    
    container.innerHTML = html;
}

// 加载筹码分布数据
async function loadCyqData() {
    if (document.getElementById('cyq-content').innerHTML.includes('加载中')) return;
    
    showLoading('cyq-content');
    
    try {
        const response = await apiRequest(`/stocks/${tsCode}/cyq?limit=20`);
        if (response.code === 200) {
            renderCyqData(response.data);
        } else {
            showError('cyq-content', '筹码分布数据加载失败');
        }
    } catch (error) {
        showError('cyq-content', '筹码分布数据加载失败');
        console.error('加载筹码分布数据失败:', error);
    }
}

// 渲染筹码分布数据
function renderCyqData(data) {
    const container = document.getElementById('cyq-content');
    
    if (!data || data.length === 0) {
        container.innerHTML = '<div class="text-center py-4"><p class="text-muted">暂无筹码分布数据</p></div>';
        return;
    }
    
    const html = `
        <div class="mb-3">
            <small class="text-muted">筹码分布数据，共 ${data.length} 条记录</small>
        </div>
        
        <!-- 筹码分布图表 -->
        <div class="row mb-4">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">
                        <h6 class="mb-0">📊 成本分位曲线</h6>
                    </div>
                    <div class="card-body">
                        <div id="cost-distribution-chart" style="height: 400px;"></div>
                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="card">
                    <div class="card-header">
                        <h6 class="mb-0">📈 胜率变化</h6>
                    </div>
                    <div class="card-body">
                        <div id="winner-rate-chart" style="height: 400px;"></div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 筹码分析指标 -->
        <div class="row mb-4">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h6 class="mb-0">🎯 筹码分析指标</h6>
                    </div>
                    <div class="card-body">
                        <div class="row" id="cyq-indicators">
                            <!-- 动态生成指标卡片 -->
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 详细数据表格 -->
        <div class="card">
            <div class="card-header">
                <h6 class="mb-0">📋 详细数据</h6>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-sm table-hover">
                        <thead>
                            <tr>
                                <th>日期</th>
                                <th>历史最低</th>
                                <th>历史最高</th>
                                <th>5%成本</th>
                                <th>15%成本</th>
                                <th>50%成本</th>
                                <th>85%成本</th>
                                <th>95%成本</th>
                                <th>加权平均</th>
                                <th>胜率</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${data.slice(0, 10).map(item => `
                                <tr>
                                    <td>${item.trade_date || '--'}</td>
                                    <td class="text-success">${formatNumber(item.his_low, 2)}</td>
                                    <td class="text-danger">${formatNumber(item.his_high, 2)}</td>
                                    <td>${formatNumber(item.cost_5pct, 2)}</td>
                                    <td>${formatNumber(item.cost_15pct, 2)}</td>
                                    <td><strong>${formatNumber(item.cost_50pct, 2)}</strong></td>
                                    <td>${formatNumber(item.cost_85pct, 2)}</td>
                                    <td>${formatNumber(item.cost_95pct, 2)}</td>
                                    <td class="text-primary"><strong>${formatNumber(item.weight_avg, 2)}</strong></td>
                                    <td class="${(item.winner_rate || 0) >= 50 ? 'text-success' : 'text-danger'}">
                                        <strong>${formatPercent(item.winner_rate || 0)}</strong>
                                    </td>
                                </tr>
                            `).join('')}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    `;
    
    container.innerHTML = html;
    
    // 渲染图表
    renderCyqCharts(data);
}

// 渲染筹码分布图表
function renderCyqCharts(data) {
    // 成本分位曲线图
    const costChart = echarts.init(document.getElementById('cost-distribution-chart'));
    
    const dates = data.map(item => item.trade_date).reverse();
    
    const costOption = {
        title: {
            text: '成本分位曲线',
            left: 'center'
        },
        tooltip: {
            trigger: 'axis',
            formatter: function(params) {
                let result = params[0].name + '<br/>';
                params.forEach(param => {
                    result += param.marker + param.seriesName + ': ' + formatNumber(param.value, 2) + '<br/>';
                });
                return result;
            }
        },
        legend: {
            data: ['5%成本', '15%成本', '50%成本', '85%成本', '95%成本', '加权平均'],
            top: 30
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '15%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: dates,
            axisLabel: {
                rotate: 45
            }
        },
        yAxis: {
            type: 'value',
            axisLabel: {
                formatter: function(value) {
                    return formatNumber(value, 2);
                }
            }
        },
        series: [
            {
                name: '5%成本',
                type: 'line',
                data: data.map(item => item.cost_5pct || 0).reverse(),
                itemStyle: { color: '#ff7875' }
            },
            {
                name: '15%成本',
                type: 'line',
                data: data.map(item => item.cost_15pct || 0).reverse(),
                itemStyle: { color: '#ffa940' }
            },
            {
                name: '50%成本',
                type: 'line',
                data: data.map(item => item.cost_50pct || 0).reverse(),
                itemStyle: { color: '#1890ff' },
                lineStyle: { width: 3 }
            },
            {
                name: '85%成本',
                type: 'line',
                data: data.map(item => item.cost_85pct || 0).reverse(),
                itemStyle: { color: '#73d13d' }
            },
            {
                name: '95%成本',
                type: 'line',
                data: data.map(item => item.cost_95pct || 0).reverse(),
                itemStyle: { color: '#b37feb' }
            },
            {
                name: '加权平均',
                type: 'line',
                data: data.map(item => item.weight_avg || 0).reverse(),
                itemStyle: { color: '#f759ab' },
                lineStyle: { width: 2, type: 'dashed' }
            }
        ]
    };
    
    costChart.setOption(costOption);
    
    // 胜率变化图
    const winnerChart = echarts.init(document.getElementById('winner-rate-chart'));
    
    const winnerOption = {
        title: {
            text: '胜率变化',
            left: 'center'
        },
        tooltip: {
            trigger: 'axis',
            formatter: function(params) {
                const data = params[0];
                return `${data.name}<br/>胜率: ${formatPercent(data.value)}`;
            }
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '15%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: dates,
            axisLabel: {
                rotate: 45
            }
        },
        yAxis: {
            type: 'value',
            min: 0,
            max: 100,
            axisLabel: {
                formatter: function(value) {
                    return value + '%';
                }
            }
        },
        series: [{
            name: '胜率',
            type: 'line',
            data: data.map(item => item.winner_rate || 0).reverse(),
            itemStyle: {
                color: '#52c41a'
            },
            areaStyle: {
                color: {
                    type: 'linear',
                    x: 0,
                    y: 0,
                    x2: 0,
                    y2: 1,
                    colorStops: [{
                        offset: 0, color: 'rgba(82, 196, 26, 0.3)'
                    }, {
                        offset: 1, color: 'rgba(82, 196, 26, 0.1)'
                    }]
                }
            },
            markLine: {
                data: [
                    { yAxis: 50, name: '50%基准线' }
                ],
                lineStyle: {
                    color: '#ff4d4f',
                    type: 'dashed'
                }
            }
        }]
    };
    
    winnerChart.setOption(winnerOption);
    
    // 渲染筹码分析指标
    renderCyqIndicators(data[0]); // 最新数据
    
    // 响应式调整
    window.addEventListener('resize', function() {
        costChart.resize();
        winnerChart.resize();
    });
}

// 渲染筹码分析指标
function renderCyqIndicators(data) {
    const container = document.getElementById('cyq-indicators');
    
    // 计算筹码集中度（95%成本 - 5%成本）/ 50%成本
    const concentration = data.cost_95pct && data.cost_5pct && data.cost_50pct ? 
        ((data.cost_95pct - data.cost_5pct) / data.cost_50pct * 100) : 0;
    
    // 计算当前价格相对位置（需要从股票基本信息获取当前价格）
    const currentPrice = stockInfo?.latest_daily?.close || 0;
    const pricePosition = data.cost_95pct && data.cost_5pct ? 
        ((currentPrice - data.cost_5pct) / (data.cost_95pct - data.cost_5pct) * 100) : 0;
    
    const html = `
        <div class="col-md-3">
            <div class="text-center p-3 bg-light rounded">
                <h5 class="text-primary">${formatNumber(concentration, 1)}%</h5>
                <small class="text-muted">筹码集中度</small>
            </div>
        </div>
        <div class="col-md-3">
            <div class="text-center p-3 bg-light rounded">
                <h5 class="text-success">${formatNumber(data.weight_avg || 0, 2)}</h5>
                <small class="text-muted">加权平均成本</small>
            </div>
        </div>
        <div class="col-md-3">
            <div class="text-center p-3 bg-light rounded">
                <h5 class="${(data.winner_rate || 0) >= 50 ? 'text-success' : 'text-danger'}">${formatPercent(data.winner_rate || 0)}</h5>
                <small class="text-muted">当前胜率</small>
            </div>
        </div>
        <div class="col-md-3">
            <div class="text-center p-3 bg-light rounded">
                <h5 class="text-warning">${formatNumber(pricePosition, 1)}%</h5>
                <small class="text-muted">价格相对位置</small>
            </div>
        </div>
    `;
    
    container.innerHTML = html;
}

// 快速操作函数
function addToWatchlist() {
    alert(`已将 ${stockInfo?.name || tsCode} 加入自选股`);
}

function openAnalysis() {
    window.open(`/analysis?stock=${tsCode}`, '_blank');
}

function openBacktest() {
    window.open(`/backtest?stock=${tsCode}`, '_blank');
}

// 工具函数
function formatNumber(num, decimals = 2) {
    if (num === null || num === undefined || isNaN(num)) return '--';
    return Number(num).toLocaleString('zh-CN', {
        minimumFractionDigits: decimals,
        maximumFractionDigits: decimals
    });
}

function formatPercent(num) {
    if (num === null || num === undefined || isNaN(num)) return '--';
    const sign = num >= 0 ? '+' : '';
    return sign + Number(num).toFixed(2) + '%';
}

// AI分析相关函数
let currentAIAnalysis = null;

// 初始化AI分析Tab
function initAIAnalysisTab() {
    // Tab切换时不需要特殊处理，用户点击按钮触发分析
    console.log('AI分析Tab已激活');
}

// 开始AI分析
async function startAIAnalysis(depth = 'standard') {
    const container = document.getElementById('ai-summary-content');

    // 显示分析进行中的界面
    showAIAnalysisLoading(container, depth);

    try {
        // 构建分析请求
        const requestData = {
            stock_code: tsCode,
            config: {
                analysts: ['market', 'fundamentals', 'news'],
                depth: depth,
                llm_provider: 'dashscope',
                model: depth === 'quick' ? 'qwen-turbo' : 'qwen-plus',
                include_quantitative_data: true
            }
        };

        // 发送分析请求到TradingAgents-CN API
        const response = await fetch('http://localhost:8000/api/v1/analyze_stock', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(requestData)
        });

        const result = await response.json();

        if (result.success) {
            currentAIAnalysis = result.data;
            renderAIAnalysisResult(container, result.data);

            // 显示详细分析和回测部分
            document.getElementById('multi-agent-details').style.display = 'block';
            document.getElementById('ai-backtest-section').style.display = 'block';

            // 渲染多智能体分析详情
            renderMultiAgentDetails(result.data);

            // 渲染AI决策回测图表
            renderAIBacktestChart(result.data);
        } else {
            showAIAnalysisError(container, result.error || '分析失败');
        }

    } catch (error) {
        console.error('AI分析失败:', error);
        showAIAnalysisError(container, '网络错误，请检查AI服务是否启动');
    }
}

// 显示AI分析加载状态
function showAIAnalysisLoading(container, depth) {
    const depthText = {
        'quick': '快速分析',
        'standard': '标准分析',
        'deep': '深度分析'
    };

    const estimatedTime = {
        'quick': '1-2分钟',
        'standard': '2-3分钟',
        'deep': '3-5分钟'
    };

    container.innerHTML = `
        <div class="text-center py-5">
            <div class="mb-4">
                <div class="spinner-border text-primary" style="width: 3rem; height: 3rem;" role="status">
                    <span class="visually-hidden">分析中...</span>
                </div>
            </div>
            <h5 class="text-primary">🤖 AI正在分析中...</h5>
            <p class="text-muted">正在进行${depthText[depth]}，预计需要 ${estimatedTime[depth]}</p>
            <div class="progress mx-auto" style="width: 300px;">
                <div class="progress-bar progress-bar-striped progress-bar-animated"
                     role="progressbar" style="width: 100%"></div>
            </div>
            <div class="mt-4">
                <small class="text-muted">
                    <i class="fas fa-info-circle"></i>
                    AI正在调用多个智能体进行协同分析，请耐心等待...
                </small>
            </div>
        </div>
    `;
}

// 显示AI分析错误
function showAIAnalysisError(container, message) {
    container.innerHTML = `
        <div class="text-center py-5">
            <div class="mb-3">
                <i class="fas fa-exclamation-triangle fa-3x text-warning"></i>
            </div>
            <h5 class="text-warning">分析失败</h5>
            <p class="text-muted">${message}</p>
            <button class="btn btn-primary" onclick="startAIAnalysis('quick')">
                重新分析
            </button>
        </div>
    `;
}

// 渲染AI分析结果摘要
function renderAIAnalysisResult(container, data) {
    const ratingColor = {
        'BUY': 'success',
        'STRONG_BUY': 'success',
        'SELL': 'danger',
        'STRONG_SELL': 'danger',
        'HOLD': 'warning'
    };

    const ratingText = {
        'BUY': '买入',
        'STRONG_BUY': '强烈买入',
        'SELL': '卖出',
        'STRONG_SELL': '强烈卖出',
        'HOLD': '持有'
    };

    const color = ratingColor[data.overall_rating] || 'secondary';
    const rating = ratingText[data.overall_rating] || data.overall_rating;

    container.innerHTML = `
        <div class="row">
            <div class="col-md-8">
                <div class="row mb-4">
                    <div class="col-md-4">
                        <div class="text-center">
                            <h3 class="text-${color} mb-2">${rating}</h3>
                            <small class="text-muted">综合评级</small>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="text-center">
                            <h3 class="text-${color} mb-2">${(data.confidence_score * 100).toFixed(0)}%</h3>
                            <small class="text-muted">信心指数</small>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="text-center">
                            <h3 class="text-primary mb-2">${data.target_price ? '¥' + data.target_price.toFixed(2) : '--'}</h3>
                            <small class="text-muted">AI目标价</small>
                        </div>
                    </div>
                </div>
                <div class="alert alert-${color} border-0">
                    <h6><i class="fas fa-lightbulb me-2"></i>一句话总结</h6>
                    <p class="mb-0">${data.summary}</p>
                </div>
            </div>
            <div class="col-md-4">
                <div class="text-center">
                    <canvas id="confidence-gauge" width="200" height="200"></canvas>
                </div>
            </div>
        </div>
    `;

    // 渲染信心指数仪表盘
    renderConfidenceGauge(data.confidence_score, data.risk_score);
}

// 渲染多智能体分析详情
function renderMultiAgentDetails(data) {
    const container = document.getElementById('agentAnalysisAccordion');

    if (!data.agents_opinions || data.agents_opinions.length === 0) {
        container.innerHTML = '<p class="text-muted text-center py-3">暂无智能体分析详情</p>';
        return;
    }

    const agentIcons = {
        'market': '📈',
        'fundamentals': '🏢',
        'news': '📰',
        'social': '💬'
    };

    const agentNames = {
        'market': '技术分析师',
        'fundamentals': '基本面分析师',
        'news': '新闻分析师',
        'social': '社交媒体分析师'
    };

    const accordionHTML = data.agents_opinions.map((opinion, index) => {
        const icon = agentIcons[opinion.agent_type] || '🤖';
        const name = agentNames[opinion.agent_type] || opinion.agent_type;
        const isFirst = index === 0;

        return `
            <div class="accordion-item">
                <h2 class="accordion-header" id="heading${index}">
                    <button class="accordion-button ${isFirst ? '' : 'collapsed'}" type="button"
                            data-bs-toggle="collapse" data-bs-target="#collapse${index}">
                        ${icon} ${name}
                        <span class="badge bg-primary ms-2">评分: ${opinion.score.toFixed(2)}</span>
                        <span class="badge bg-success ms-1">置信度: ${(opinion.confidence * 100).toFixed(0)}%</span>
                    </button>
                </h2>
                <div id="collapse${index}" class="accordion-collapse collapse ${isFirst ? 'show' : ''}"
                     data-bs-parent="#agentAnalysisAccordion">
                    <div class="accordion-body">
                        <div class="row">
                            <div class="col-md-8">
                                <h6>分析观点</h6>
                                <p>${opinion.opinion}</p>
                            </div>
                            <div class="col-md-4">
                                <div class="text-center">
                                    <div class="progress mb-2" style="height: 20px;">
                                        <div class="progress-bar bg-primary" style="width: ${opinion.score * 20}%">
                                            ${opinion.score.toFixed(2)}
                                        </div>
                                    </div>
                                    <small class="text-muted">评分 (0-5)</small>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `;
    }).join('');

    container.innerHTML = accordionHTML;
}

// 渲染信心指数仪表盘
function renderConfidenceGauge(confidence, risk) {
    const canvas = document.getElementById('confidence-gauge');
    if (!canvas) return;

    const ctx = canvas.getContext('2d');
    const centerX = canvas.width / 2;
    const centerY = canvas.height / 2;
    const radius = 80;

    // 清空画布
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    // 绘制背景圆
    ctx.beginPath();
    ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI);
    ctx.strokeStyle = '#e9ecef';
    ctx.lineWidth = 12;
    ctx.stroke();

    // 绘制信心指数弧
    const confidenceAngle = (confidence * 2 * Math.PI) - Math.PI / 2;
    ctx.beginPath();
    ctx.arc(centerX, centerY, radius, -Math.PI / 2, confidenceAngle);
    ctx.strokeStyle = confidence > 0.7 ? '#28a745' : confidence > 0.5 ? '#ffc107' : '#dc3545';
    ctx.lineWidth = 12;
    ctx.stroke();

    // 绘制中心文字
    ctx.fillStyle = '#333';
    ctx.font = 'bold 24px Arial';
    ctx.textAlign = 'center';
    ctx.fillText(`${(confidence * 100).toFixed(0)}%`, centerX, centerY + 8);

    // 绘制标签
    ctx.font = '14px Arial';
    ctx.fillStyle = '#666';
    ctx.fillText('信心指数', centerX, centerY + 30);
}

// 渲染AI决策回测图表
function renderAIBacktestChart(data) {
    const canvas = document.getElementById('aiBacktestChart');
    if (!canvas) return;

    // 这里应该使用真实的回测数据，现在使用模拟数据
    const mockBacktestData = generateMockBacktestData();

    const ctx = canvas.getContext('2d');

    // 使用Chart.js创建图表
    new Chart(ctx, {
        type: 'line',
        data: {
            labels: mockBacktestData.dates,
            datasets: [
                {
                    label: 'AI策略收益',
                    data: mockBacktestData.aiStrategy,
                    borderColor: '#28a745',
                    backgroundColor: 'rgba(40, 167, 69, 0.1)',
                    borderWidth: 3,
                    fill: false
                },
                {
                    label: '持股不动',
                    data: mockBacktestData.buyHold,
                    borderColor: '#007bff',
                    backgroundColor: 'rgba(0, 123, 255, 0.1)',
                    borderWidth: 2,
                    fill: false
                },
                {
                    label: '基准指数',
                    data: mockBacktestData.benchmark,
                    borderColor: '#6c757d',
                    backgroundColor: 'rgba(108, 117, 125, 0.1)',
                    borderWidth: 1,
                    borderDash: [5, 5],
                    fill: false
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                title: {
                    display: true,
                    text: 'AI决策策略回测对比'
                },
                legend: {
                    position: 'top'
                }
            },
            scales: {
                y: {
                    beginAtZero: false,
                    title: {
                        display: true,
                        text: '累计收益率 (%)'
                    },
                    ticks: {
                        callback: function(value) {
                            return value.toFixed(1) + '%';
                        }
                    }
                },
                x: {
                    title: {
                        display: true,
                        text: '日期'
                    }
                }
            },
            interaction: {
                intersect: false,
                mode: 'index'
            }
        }
    });
}

// 生成模拟回测数据
function generateMockBacktestData() {
    const dates = [];
    const aiStrategy = [];
    const buyHold = [];
    const benchmark = [];

    const startDate = new Date();
    startDate.setFullYear(startDate.getFullYear() - 1);

    let aiReturn = 0;
    let buyHoldReturn = 0;
    let benchmarkReturn = 0;

    for (let i = 0; i < 252; i++) { // 一年的交易日
        const date = new Date(startDate);
        date.setDate(date.getDate() + i);
        dates.push(date.toLocaleDateString('zh-CN', { month: 'short', day: 'numeric' }));

        // 模拟AI策略表现更好
        aiReturn += (Math.random() - 0.45) * 2; // 略微正偏
        buyHoldReturn += (Math.random() - 0.48) * 1.8;
        benchmarkReturn += (Math.random() - 0.5) * 1.5;

        aiStrategy.push(aiReturn);
        buyHold.push(buyHoldReturn);
        benchmark.push(benchmarkReturn);
    }

    return { dates, aiStrategy, buyHold, benchmark };
}
</script>
{% endblock %}